#include "widget.h"
#include "ui_widget.h"
#include <QListWidgetItem>
#include <QDebug>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    ui->lineEdit->setPlaceholderText("请输入要添加的编程语言");

//    ui->listWidget->addItem("C++");
    ui->listWidget->addItem(new QListWidgetItem(QIcon(":/image/C++.png"),"C++"));
    ui->listWidget->addItem(new QListWidgetItem(QIcon(":/image/java.png"),"JAVA"));
    ui->listWidget->addItem(new QListWidgetItem(QIcon(":/image/Python.png"),"Python"));

    //默认按文本排序
    ui->listWidget->sortItems();
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_add_clicked()
{
    //将lineEdit中的文本添加到listWidget中
    const QString &text = ui->lineEdit->text();

    ui->listWidget->addItem(text);
}

void Widget::on_pushButton_delete_clicked()
{
    //先获取到选中的项
    int row = ui->listWidget->currentRow();

    ui->listWidget->takeItem(row);
}

void Widget::on_listWidget_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous)
{
    //当选中的项发送变化时，触发信号
    if(current != nullptr){
        qDebug() << "当前选中：" << current->text();
    }
    if(previous != nullptr){
        qDebug() << "上次选中：" + previous->text();
    }
}

bool sortByLength(const QListWidgetItem *item1,const QListWidgetItem *item2)
{
    return item1->text().length() - item2->text().length();
}

void Widget::on_pushButton_sort_clicked()
{
    ui->listWidget->sortItems();
}

